package com.katyushateam.ImageRecognitionApp;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;

import com.google.android.material.progressindicator.LinearProgressIndicator;

import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Date;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class MainActivity extends AppCompatActivity {

    static final int REQUEST_IMAGE_CAPTURE = 1;
    static final String TAG = "katyushateam";

    String currentPhotoPath;

    Button btn_capture;
    LinearProgressIndicator lpi_wait;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn_capture = findViewById(R.id.btn_capture);
        lpi_wait = findViewById(R.id.lpi_wait);

        btn_capture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //调用系统相机
                dispatchTakePictureIntent();
            }
        });
    }

    /**
     *  调用后响应
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {

            lpi_wait.setVisibility(View.VISIBLE);

            //压缩图片
            compressPic(currentPhotoPath);
            //调用百度api获取json
            new Http_Thread().start();
        }
    }

    /**
     * 调用系统相机
     */
    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                Uri photoURI = FileProvider.getUriForFile(this,
                        "com.katyushateam.ImageRecognitionApp.FileProvider",
                        photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
            }
        }
    }

    /**
     * 压缩指定路径的图片保存到应用私有文件夹
     * @param photoPath 要压缩的图片的路径
     */
    private void compressPic(String photoPath)
    {
        Luban.with(this)
                .load(photoPath)
                .ignoreBy(100)
                .setTargetDir(getExternalFilesDir("/compressedPics").toString())
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        //压缩开始前调用，可以在方法内启动 loading UI
                    }

                    @Override
                    public void onSuccess(File file) {
                        //压缩成功后调用，返回压缩后的图片文件
                        currentPhotoPath = file.getAbsolutePath();
                    }

                    @Override
                    public void onError(Throwable e) {
                        //当压缩过程出现问题时调用
                        e.printStackTrace();
                    }
                }).launch();
    }

    /**
     * 创建图片文件
     */
    private File createImageFile() throws IOException {
        // Create an image file name
        @SuppressLint("SimpleDateFormat")
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir("/capturedPics");
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        currentPhotoPath = image.getAbsolutePath();
        return image;
    }

    private class Http_Thread extends Thread{
        @Override
        public void run() {
            String json = Ingredient.ingredient(currentPhotoPath);
            Bundle data = new Bundle();
            data.putString("json", json);
            Message msg = new Message();
            msg.what = 1;
            msg.setData(data);
            codeHandler.sendMessage(msg);
        }
    }

    private final MyHandle codeHandler=new MyHandle(MainActivity.this);
    private static class MyHandle extends Handler
    {
        WeakReference<MainActivity> mActivityWeakReference;
        public MyHandle(MainActivity mActivity){
            mActivityWeakReference = new WeakReference<>(mActivity);
        }
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            MainActivity activity = mActivityWeakReference.get();
            switch(msg.what){
                case 1:
                    activity.showResult(msg);
                    break;
            }
            super.handleMessage(msg);
        }
    }

    private void showResult(Message msg){
        String str_json = msg.getData().getString("json");

        Intent intent = new Intent(MainActivity.this, ResultActivity.class);
        intent.putExtra("send_json", str_json);
        lpi_wait.setVisibility(View.INVISIBLE);
        startActivity(intent);
    }
}